<script setup lang="ts">
  import { onMounted, ref } from 'vue'
  import type { Ref } from 'vue'
  import { IotApi } from '../js/apis';
  import { DeviceInfo } from '../js/entities';
  import router  from '../router/index';

  const devices: Ref<DeviceInfo[]> = ref([]);
  onMounted(()=>{
    IotApi.get_device_list().then(
      function fulfilled(value){
        devices.value = value
      },
      function rejected(reason){
        console.log(reason);
        alert(reason)
      }
    ).catch((reason)=>{
      alert(reason);
      console.log(reason);
    });
  });

  function get_state_name(device: DeviceInfo): string{
    if(device.enable){
      if(device.online){
        if (device.empty){
          return '缺粮';
        }else{
          return '在线';
        }
      }else{
        return '离线';
      }
    }else{
      return '禁用';
    }
  }

  function device_icon(device: DeviceInfo): string{
    let img_file_name = device.type.icon_url;
    return new URL('../assets/'+img_file_name, import.meta.url).href; //device.type.icon_url;
  }

  function do_setting(device: DeviceInfo){
    //alert(device);
    router.push({name:'edit_pet_feeder_setting', params:{device_id: device.id, title: device.name}});
  }
</script>

<template>
    <div class="items">
      <div class="item" @click="do_setting(device)" v-for="device in devices">
        <img :src="device_icon(device)">
        <label class="label">{{device.name}}</label>
        <div class="state">{{get_state_name(device)}}</div>
      </div>
    </div>
  </template>
  
  <style scoped>
  .items {
    margin: 0;
    display:flex;
    align-content: flex-start;
    flex-direction: row;
    flex-wrap: wrap;
    justify-items: left;
    height: 100%;
    width: 100%;
  }
  
  .item{
    display: flex;
    flex-direction: column;
    align-items: center;
    position: relative;
    margin: 1rem;
    border: none;
    /*border-style: dashed;
    border-color: blue;*/
    height: min-content;
  }

  .item img{
    margin: 5px;
    width: 64px;
    height: 64px;
  }

  .state {
    position: absolute;
    top: 0;
    right: 0;
    height: 1rem;
    font-size: smaller;
  }
  
  .item label{
    font-family: '黑体', Courier, monospace;
    font-size: medium;
    text-align: center;
    height: 1rem;
    display: block; /* 或者 inline-block */
    width: 5rem; /* 设置固定宽度 */
    white-space: nowrap; /* 确保文本不换行 */
    overflow: hidden; /* 超出部分隐藏 */
    text-overflow: ellipsis; /* 使用省略号表示被截断的文本 */
  }
  </style>
  